import fileService from '@/service/common/file.service';
import common, { isValue, nullC } from '@/util/common';

/**
*@Author: QWP
*@Description: 附件下载,通过id下载
*@Params: // type = more: 批量下载  , sigle: 单个下载, fileParams: 附件配置及参数
*@Date 2023-09-06 21:06
*/
export const downloadFiles = (type, data, fileParams) => {
  if(type == 'more' && data.length == 0)  {
    common.alertC("请先选择要下载的数据!");
    return
  }

  let ids = data.map(item => item['keyid']).filter(item => common.isValue(item));
  
  if(ids.length == 0) {
    common.alertC("选中数据没有附件信息!");
    return
  }
  
  fileService.downloads(Object.assign({ ids }, fileParams)).then(res => {
    common.alertC("下载成功!", "success")
  })
  .catch(() => {})
}

/**
*@Author: QWP
*@Description: 附件下载: 通过地址
*@Params: // type = more: 批量下载  , sigle: 单个下载, fileParams: 附件配置及参数
*@Date 2023-09-06 21:06
*/
export const downloadFileUrls = (type, data, fileParams) => {
  if(type == 'more' && data.length == 0)  {
    common.alertC("请先选择要下载的数据!");
    return
  }

  let path = [];
  path = data.filter(o => isValue(o['filepath']))
    .map(o => { 
      return { url: nullC(o['filepath']), originalfilename: nullC(o['filename']) }
    })
  if(path.length == 0) {
    common.alertC("选中数据没有附件信息!");
    return
  }
  
  return new Promise((resolve, reject) => {
    fileService.downloadsPath({ path, ...fileParams }).then(res => {
      resolve();
      common.alertC("下载成功!", "success")
    })
    .catch(() => reject())
  }) 
}

/**
*@Author: QWP
*@Description: 获取扁平表头
*@Date 2023-09-27 16:52
*/
export const flatCanEditCols = (columns) => {
  let cols = [];
  const flat = (data) => {
    data.forEach(item => {
      if((item['children'] || []).length == 0) {
        cols.push(item)
      }
      else {
        flat(item.children)
      }
    })
  }
  flat(columns)
  const result = cols.filter(item => !['text_money', 'icon', 'text', 'link', 'textBtn'].includes(item['ctype']) && isValue(item['ctype']))
  return result;
} 

/**
*@Author: QWP
*@Description: 创建首位呼应对象
*@Date 2023-09-27 16:52
*/
export const itemNextItem = (data = [], props = { id: 'key' }) => {
  let result = {};
  data.forEach((item, index) => {
    let next = index == data.length - 1 ? null : nullC(data[index + 1][props['id']]);
    if(index == 0) {
      result['first_key'] = {
        key: item[props['id']],
        next
      };
    }
    result[item[props['id']]] = { ...item, next }
  })
  return result;
}